
package com.zy.config;

import com.zy.entity.Staff;
import com.zy.mapper.StaffMapper;
import com.zy.service.MenuService;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource.Util;

public class MyRealm extends AuthorizingRealm {

    @Resource
    StaffMapper staffMapper;

    @Resource
    MenuService menuService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Staff s = (Staff)principalCollection.getPrimaryPrincipal();
        Set<String> menuSet = (Set)this.menuService.getByAccountName(s.getSfUser()).stream().collect(Collectors.toSet());
        System.out.println("此用户拥有的权限字符串" + menuSet);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(menuSet);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String account = (String)authenticationToken.getPrincipal();
        Staff staff = new Staff();
        staff.setSfUser(account);
        Staff staff1 = (Staff)this.staffMapper.selectOne(staff);
        return staff1 != null ? new SimpleAuthenticationInfo(staff1, staff1.getSfPassword(), Util.bytes(staff1.getSfSalf()), this.getName()) : null;
    }
}
